﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using DB;

namespace ProductManage
{
    public partial class FormGetEbaoProducts : Form
    {
        private int iListUrl = 0;
        private string strPath = @"C:\Alex\Ebao";
        private string strUrlPath = @"http://www.ebaopifa.com/products.php?id={0}&sortby=timedown&p={1}";
        private int iCa = 1;
        private int iPage = 1;

        public FormGetEbaoProducts()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ReloadListUrl();
            this.webBrowser1.DocumentCompleted -= webBrowser1_DocumentCompleted_LoadProduct;
            this.webBrowser1.DocumentCompleted -= webBrowser1_DocumentCompleted_loadProductList;
            this.webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted_LoadProduct;
            iListUrl = 0;
            while (iListUrl++ < listProducts.Count - 1)
            {
                var product = listProducts[iListUrl];
                if (string.IsNullOrEmpty(product.SKU))
                {
                    deal(product.EbaoURL);
                    return;
                }
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            ReloadListUrl();
            this.webBrowser1.DocumentCompleted -= webBrowser1_DocumentCompleted_LoadProduct;
            this.webBrowser1.DocumentCompleted -= webBrowser1_DocumentCompleted_loadProductList;
            this.webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted_loadProductList;
            iCa = Convert.ToInt32(this.textBoxGetProductsStart.Text);
            iPage = 1;
            this.Text = "Working";
            deal(string.Format(this.strUrlPath, iCa, iPage));
        }

        #region webBrowser1
        void webBrowser1_DocumentCompleted_LoadProduct(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.Document != null)
            {
                try
                {
                    var document = webBrowser1.Document;
                    var pics = GetPicUrl(document);
                    var detail = GetProductDetail(document);
                    if (detail.ContainsKey("编号"))
                    {
                        var strUrl = webBrowser1.Url.ToString();
                        var code = detail["编号"];
                        var weight = detail["重量"].Replace("克", "").Replace(" ", "");
                        var size = detail["尺寸"];
                        var color = detail["颜色"];
                        var invertory = detail["库存"] == "有货"?999:0;
                        var price = detail["价格"].Replace("￥", "").Replace("元", "").Replace(" ", "");

                        int i = 1;
                        foreach (var pic in pics)
                        {
                            string localPath = strPath + @"\Image\" + code +"_PIC"+i+++ ".jpg";
                            WebClient mywebclient = new WebClient();
                            mywebclient.DownloadFile(pic, localPath);
                        }

                        var product = listProducts[iListUrl];
                        product.SKU = code;
                        product.Weight = weight;
                        product.Size = size;
                        product.Color = color;
                        product.EbaoInventory = invertory;
                        product.PricePurchase = Convert.ToDecimal(price);
                        ProductsDb.DbMysql.SetProdutSku(product);
                    }

                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }


            }
            while (iListUrl++ < listProducts.Count - 1)
            {
                var product = listProducts[iListUrl];
                if (string.IsNullOrEmpty(product.SKU))
                {
                    deal(product.EbaoURL);
                    return;
                }
            }
            this.Text = "Done";
        }
        
        void webBrowser1_DocumentCompleted_loadProductList(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.Document != null)
            {
                try
                {
                    var document = webBrowser1.Document;
                    var urls = GetProductUrls(document);


                    foreach (var url in urls)
                    {
                        if (!dicUrls.ContainsKey(url))
                        {
                            var product = new Product() {EbaoURL = url};
                            product.Feature = iCa.ToString();
                            dicUrls.Add(url, product);
                            ProductsDb.DbMysql.AddProdut(product);
                        }
                    }

                    if (urls.Count == 0)
                    {
                        iCa = iCa + 1;
                        iPage = 1;
                        if (iCa > Convert.ToInt32(this.textBoxGetProductsEnd.Text))
                        {
                            this.Text = "Done";
                            return;
                        }
                    }
                    else
                    {
                        iPage = iPage + 1;
                    }
                }
                catch
                {
                }
                deal(string.Format(this.strUrlPath, iCa, iPage));

            }
        }

        private void deal(string strUrl)
        {
            this.webBrowser1.Url = new Uri(strUrl);
        }
        #endregion

        #region Html
        private List<string> GetProductUrls(HtmlDocument strHtml)
        {
            var infos = strHtml.GetElementById("productslist");
            List<string> list = new List<string>();
            try
            {
                if (infos == null)
                    return list;
                var index = 0;
                while (infos.InnerHtml.IndexOf("<A href=\"", index + 1) > 0)
                {
                    index = infos.InnerHtml.IndexOf("<A href=\"", index + 1);
                    var endIndex = infos.InnerHtml.IndexOf("\"", index + 9);
                    list.Add(@"http://www.ebaopifa.com" + infos.InnerHtml.Substring(index + 9, endIndex - index - 9));
                }
            }
            catch (Exception)
            {
            }
            return list;
        }
        private List<string> GetPicUrl(HtmlDocument strHtml)
        {
            var infos = strHtml.GetElementById("productintro");
            List<string> list = new List<string>();
            try
            {
                if (infos == null)
                    return list;
                var index = 0;
                while (infos.InnerHtml.IndexOf("<IMG src=\"/products/", index + 1) > 0)
                {
                    index = infos.InnerHtml.IndexOf("<IMG src=\"/products/", index + 1);
                    var endIndex = infos.InnerHtml.IndexOf("\">", index);
                    var url = @"http://www.ebaopifa.com/" + infos.InnerHtml.Substring(index + 10, endIndex - index - 10);
                    if (!url.Contains("gif"))
                        list.Add(url);
                }
            }
            catch
            {
            }
            return list;
        }
        private Dictionary<string, string> GetProductDetail(HtmlDocument strHtml)
        {
            var infos = strHtml.GetElementById("form1");
            Dictionary<string, string> list = new Dictionary<string, string>();
            try
            {
                if (infos == null)
                    return list;
                var text = infos.InnerText;
                StringReader reader = new StringReader(text);
                var strLine = reader.ReadLine();
                while (!string.IsNullOrEmpty(strLine))
                {
                    if (strLine.Contains("："))
                    {
                        var t = strLine.Split('：');
                        if (!list.ContainsKey(t[0]))
                        {
                            list.Add(t[0].Trim(), t[1].Trim());
                        }
                    }
                    strLine = reader.ReadLine();
                }
            }
            catch (Exception)
            {
            }

            return list;
        }
        #endregion

        #region txt
        private void ReloadListUrl()
        {
            listProducts = ProductsDb.DbMysql.GetAllProducts();
            foreach (Product product in listProducts)
            {
                if (!dicUrls.ContainsKey(product.EbaoURL))
                {
                    dicUrls.Add(product.EbaoURL, product);
                }
            }
        }
        private Dictionary<string ,Product> dicUrls = new Dictionary<string, Product>(); 
        private List<Product> listProducts = new List<Product>();
        #endregion

        
    }
}
